package com.itheima.dao;

import com.itheima.domain.Message;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface MessageMapper {
    @Insert("insert into message values(#{id}, #{content}, #{sendId}, #{receiveId}, #{conversationId}, #{time}, #{status})")
    void insert(Message message);

    /*
     * 查询条件: 注意不需要查status
     * where sendId = #{userId} or receiveId = #{userId}
     * group by conversationId
     * */
    @Select("select conversationId, max(time) time from message where sendId = #{userId} or receiveId = #{userId} group by conversationId order by max(time) desc")
    List<Message> findConversationList(String userId);

    // 根据conversationId查，注意别人发的消息才算未读
    @Select("select count(*) from message where conversationId = #{conversationId} and receiveId = #{receiveId} and status = 0")
    Integer findConversationUnreadCount(@Param("conversationId") String conversationId, @Param("receiveId") String receiveId);

    // 根据conversationId查最新消息
    @Select("select * from message where conversationId = #{conversationId} order by time desc limit 0, 1")
    Message findConversationByConversationId(String conversationId);

    // 根据conversationId查所有消息
    @Select("select * from message where conversationId = #{conversationId} order by time desc")
    List<Message> findConversation(String conversationId);

    // 更新当前conversation所有消息status为1
    @Update("update message set status = 1 where conversationId = #{conversationId} and receiveId = #{receiveId}")
    void updateStatus(@Param("conversationId") String conversationId, @Param("receiveId") String receiveId);
}
